package midend.IR_Optimizer;

import midend.IR_Value.*;
import midend.IR_Module;
import midend.Func_Side_Effect_Analysis;
import midend.IR_Instruction.*;

import java.util.ArrayList;

public class DeadCode_Eli {
    private IR_Module module;
    private ArrayList<Instruction> useful = new ArrayList<>();

    public DeadCode_Eli(IR_Module module) {
        this.module = module;
    }

    public void Optimize() {
        Func_Side_Effect_Analysis.sideEffectAnalysis(module);
        for (IR_FuncBlock function : module.getFuncBlocks()) {
            boolean change = true;
            while (change) {
                useful.clear();
                change = false;
                for (IR_BaseBlock bb : function.get_bb_List()) {
                    ArrayList<Instruction> toBeRemoved = new ArrayList<>();
                    for (Instruction instruction : bb.get_Instruction_List()) {
                        if (module.is_Dead_Ins(instruction) ) {
                            toBeRemoved.add(instruction);
                        }
                    }
                    for (Instruction instruction : toBeRemoved) {
                        instruction.remove();
                        change = true;
                    }
                }
            }
        }
    }
}